import { Modal, Form, Input, Space, Button, App, Row, Col, Radio, Avatar, Switch } from 'antd';
import type { ModalProps } from 'antd';
import { useEffect } from 'react';
import { useBoolean } from 'ahooks';
import { MenuType } from 'src/constants';
import { AddUser, UpdateUser } from 'src/api/modules/user';
import { IUserInfo, IUserActionReqData } from 'src/interface';
import Password from 'src/components/Password';
import RoleSelect from 'src/components/RoleSelect';
import DeptTreeSelect from 'src/components/DeptTreeSelect';
import { phoneRegExp, emailRegExp } from 'src/utils/pattern';
import PermissionButton from 'src/components/Permission';
interface IProps extends ModalProps {
  data: IUserInfo | null;
  onOk?: () => void;
  onCancel?: () => void;
}

export default function UserModal(props: IProps) {
  const { data, onCancel, open, onOk, ...rest } = props;
  const [loading, { toggle }] = useBoolean(false);
  const [formInstance] = Form.useForm();
  const { message } = App.useApp();

  const onSubmit = async () => {
    const result = await formInstance.validateFields();
    if (!result) return;
    const request = data ? UpdateUser : AddUser;
    toggle();
    const requestBody = {
      ...result,
      status: result.status ? 1 : 0,
    } as IUserActionReqData;
    if (data?.userId) {
      requestBody.userId = data.userId;
    }
    try {
      await request({
        ...requestBody,
      });
      onCancel && onCancel();
      onOk && onOk();
      message.success(`用户${data ? '修改' : '新增'}成功`);
    } catch (err) {
      console.log(err);
    } finally {
      toggle();
    }
  };

  useEffect(() => {
    if (!open) return;
    formInstance.resetFields();
    if (data) {
      formInstance.setFieldsValue({
        username: data.username,
        userId: data.userId,
        mobile: data.mobile,
        email: data.email,
        status: !!data.status,
        nickname: data.nickname,
        roleIdList: (data?.roleList ?? []).map((item) => item.roleId),
        sex: data.sex,
        deptId: data.deptId,
      });
    } else {
      formInstance.setFieldsValue({
        menuType: MenuType[0].value,
        sex: 0,
        status: true,
      });
    }
  }, [open, data, formInstance]);

  return (
    <Modal
      open={open}
      {...rest}
      title={`${data ? '编辑' : '新增'}用户`}
      footer={null}
      onCancel={onCancel}>
      <Form form={formInstance} layout="vertical" labelCol={{ span: 6 }}>
        <Row gutter={16}>
          {data ? (
            <Col span={24} className="flex justify-start items-center my-[16px]">
              <Avatar size="large" src={data?.avatar} />
              <span className="ml-[8px]">{data?.username}</span>
            </Col>
          ) : (
            <>
              <Col span={24} sm={12}>
                <Form.Item
                  name="username"
                  label="用户名"
                  required
                  rules={[{ required: true, message: '请输入用户名' }]}>
                  <Input placeholder="请输入用户名" autoComplete="off" />
                </Form.Item>
              </Col>
              <Col span={24} sm={12}>
                <Form.Item
                  name="password"
                  label="密码"
                  required
                  rules={[{ required: true, message: '请输入密码' }]}>
                  <Password checkStrength={true} placeholder="请输入密码" autoComplete="off" />
                </Form.Item>
              </Col>
            </>
          )}
          <Col span={24} sm={12}>
            <Form.Item
              name="nickname"
              label="用户昵称"
              required
              rules={[{ required: true, message: '请输入用户昵称' }]}>
              <Input placeholder="请输入用户昵称" autoComplete="off" />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item
              name="mobile"
              label="手机号"
              rules={[{ message: '请输入正确的手机号', pattern: phoneRegExp }]}>
              <Input placeholder="请输入手机号" autoComplete="off" />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[{ message: '请输入邮箱地址', pattern: emailRegExp }]}>
              <Input placeholder="请输入邮箱地址" autoComplete="off" />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item name="roleIdList" label="用户角色">
              <RoleSelect />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item name="deptId" label="部门">
              <DeptTreeSelect multiple={false} />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item name="sex" label="性别">
              <Radio.Group
                options={[
                  { label: '男', value: 1 },
                  { label: '女', value: 0 },
                ]}
                optionType="button"
                buttonStyle="solid"
              />
            </Form.Item>
          </Col>
          <Col span={24} sm={12}>
            <Form.Item name="status" label="启用状态" valuePropName="checked">
              <Switch checkedChildren="开启" unCheckedChildren="关闭" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className="flex justify-end">
        {
          <Space>
            <Button disabled={loading} onClick={onCancel}>
              取消
            </Button>
            <PermissionButton
              permission={data ? 'SYSTEM_USER_UPDATE' : 'SYSTEM_USER_ADD'}
              loading={loading}
              type="primary"
              onClick={onSubmit}>
              保存
            </PermissionButton>
          </Space>
        }
      </div>
    </Modal>
  );
}
